package utils;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * Created by Lim on 2015/8/10.
 */
public class EmailSendUtils {
    private static final Log log = LogFactory.getLog(EmailSendUtils.class);
    private static final Properties pro = new Properties();

    static{
        pro.put("mail.from", "墨轨迹科技");
        pro.put("mail.smtp.host", "139.217.19.254");
        pro.put("mail.transport.protocol", "smtp");
        pro.put("mail.contentType", "text/html; charset=UTF-8");
        pro.put("mail.username", "service@nexdtech.com.cn");
        pro.put("mail.password", "Nexd2345");
    }

    /**
     * 发送邮件类
     * @param subject 邮件主题
     * @param receivingAddress 邮件接收人
     * @param body 邮件内容
     * @return
     * @throws MessagingException 发送异常
     * @throws UnsupportedEncodingException 邮件服务器配置异常
     */
    public static void sendEmail( String subject, String receivingAddress, String body)
            throws MessagingException, UnsupportedEncodingException {

        Session session = Session.getDefaultInstance(pro);

        MimeMessage msg = new MimeMessage(session);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(
                pro.getProperty("mail.username"),
                pro.getProperty("mail.from"), "UTF-8"));
        msg.setRecipients(Message.RecipientType.TO, receivingAddress);
        msg.setSubject(subject, "UTF-8");
        msg.setContent(body, pro.getProperty("mail.contentType"));
        msg.saveChanges();

        Transport transport = session.getTransport();
        transport.connect(pro.getProperty("mail.username"),
                pro.getProperty("mail.password"));//获取发件人的用户名密码 实现身份验证
        transport.sendMessage(msg, msg.getAllRecipients());

    }
}


